package com.wstuo.itsm.cim.dao;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;

import org.hibernate.criterion.CriteriaSpecification;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Disjunction;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.hibernate.transform.Transformers;
import org.springframework.transaction.annotation.Transactional;

import com.wstuo.common.dao.BaseDAOImplHibernate;
import com.wstuo.common.dto.PageDTO;
import com.wstuo.common.security.dto.UserDTO;
import com.wstuo.common.tools.dto.StatResultDTO;
import com.wstuo.common.util.DaoUtils;
import com.wstuo.common.util.MathUtils;
import com.wstuo.common.util.StringUtils;
import com.wstuo.itsm.cim.dto.CIQueryDTO;
import com.wstuo.itsm.cim.entity.CI;

/**
 * 配置项DAO类
 * 
 * @author QXY
 */
public class CIDAO extends BaseDAOImplHibernate<CI> implements ICIDAO {
	/**
	 * 配置项分页查询
	 * 
	 * @return PageDTO：
	 */
	@Transactional
	public PageDTO findPager(CIQueryDTO queryDTO, int start, int limit,
			String sidx, String sord) {

		DetachedCriteria dc = DetachedCriteria.forClass(CI.class);
		/***
		 * Set data mode
		 */
		if (queryDTO != null) {
			
			//查询关联项
			dc = searchRelation(queryDTO, dc);

			//基础属性
			dc = searchBaseAttribute(queryDTO, dc);

			//相关时间查询
			dc = searchByTime(queryDTO, dc);

			// 排序
			dc = DaoUtils.orderBy(sidx, sord, dc);
		}

		return super.findPageByCriteria(dc, start, limit,null,new String[]{sidx});
	}
	/**
	 * 相关时间查询
	 * @param queryDTO
	 * @param dc
	 */
	private DetachedCriteria searchByTime(CIQueryDTO queryDTO,  DetachedCriteria dc) {
		// 到货日期
		dc = searchArriveTime(queryDTO, dc);
		// 购买日期
		dc = searchBuyTime(queryDTO, dc);

		// 生命周期
		dc = searchLifeCycle(queryDTO, dc);
		// 警告日期
		dc = searchWarningDate(queryDTO, dc);

		// 保修期
		dc = searchWarranty(queryDTO, dc);

		// 借出时间borrowedTime
		dc = searchBorrowedTime(queryDTO, dc);

		// 报废时间wasteTime 
		dc = searchWasteTime(queryDTO, dc);

		// 回收时间recoverTime
		dc = searchRecoverTime(queryDTO, dc);

		// 预计回收时间expectedRecoverTime
		dc = searchExpectedRecoverTime(queryDTO, dc);

		// 创建时间
		dc = searchCreateTime(queryDTO, dc);
		// 最后更新时间
		dc = searchLastUpdateTime(queryDTO, dc);
		return dc;
	}
	/**
	 * 搜索生命周期
	 * @param queryDTO
	 * @param dc
	 * @return
	 */
	private DetachedCriteria searchLifeCycle(CIQueryDTO queryDTO, DetachedCriteria dc) {
		if (queryDTO.getLifeCycle() != null
				&& queryDTO.getLifeEndCycle() == null) {
			dc.add(Restrictions.ge("lifeCycle", queryDTO.getLifeCycle()));
		}
		if (queryDTO.getLifeCycle() == null
				&& queryDTO.getLifeEndCycle() != null) {
			dc.add(Restrictions.le("lifeCycle", queryDTO.getLifeEndCycle()));
		}

		if (queryDTO.getLifeCycle() != null
				&& queryDTO.getLifeEndCycle() != null) {
			dc.add(Restrictions.and(Restrictions.le("lifeCycle",
					queryDTO.getLifeEndCycle()), Restrictions.ge(
					"lifeCycle", queryDTO.getLifeCycle())));
		}
		return dc;
	}
	/**
	 * 搜索借出时间
	 * @param queryDTO
	 * @param dc
	 * @return
	 */
	private DetachedCriteria searchBorrowedTime(CIQueryDTO queryDTO, DetachedCriteria dc) {
		if (queryDTO.getBorrowedTime() != null
				&& queryDTO.getBorrowedTimeEnd() == null) {
			dc.add(Restrictions.ge("borrowedTime",
					queryDTO.getBorrowedTime()));
		}
		if (queryDTO.getBorrowedTime() == null
				&& queryDTO.getBorrowedTimeEnd() != null) {
			dc.add(Restrictions.le("borrowedTime",
					queryDTO.getBorrowedTimeEnd()));
		}

		if (queryDTO.getBorrowedTime() != null
				&& queryDTO.getBorrowedTimeEnd() != null) {
			dc.add(Restrictions.and(
					Restrictions.le("borrowedTime",
							queryDTO.getBorrowedTimeEnd()),
					Restrictions.ge("borrowedTime",
							queryDTO.getBorrowedTime())));
		}
		return dc;
	}
	/**
	 * 搜索保修期
	 * @param queryDTO
	 * @param dc
	 * @return
	 */
	private DetachedCriteria searchWarranty(CIQueryDTO queryDTO, DetachedCriteria dc) {
		if (queryDTO.getWarranty() != null
				&& queryDTO.getEndWarranty() == null) {
			dc.add(Restrictions.ge("warranty", queryDTO.getWarranty()));
		}
		if (queryDTO.getWarranty() == null
				&& queryDTO.getEndWarranty() != null) {
			dc.add(Restrictions.le("warranty", queryDTO.getEndWarranty()));
		}

		if (queryDTO.getWarranty() != null
				&& queryDTO.getEndWarranty() != null) {
			dc.add(Restrictions.and(
					Restrictions.le("warranty", queryDTO.getEndWarranty()),
					Restrictions.ge("warranty", queryDTO.getWarranty())));
		}
		return dc;
	}
	/**
	 * 搜索警告日期
	 * @param queryDTO
	 * @param dc
	 * @return
	 */
	private DetachedCriteria searchWarningDate(CIQueryDTO queryDTO, DetachedCriteria dc) {
		if (queryDTO.getWarningDate() != null
				&& queryDTO.getWarningEndDate() == null) {
			dc.add(Restrictions.ge("warningDate", queryDTO.getWarningDate()));
		}
		if (queryDTO.getWarningDate() == null
				&& queryDTO.getWarningEndDate() != null) {
			dc.add(Restrictions.le("warningDate",
					queryDTO.getWarningEndDate()));
		}

		if (queryDTO.getWarningDate() != null
				&& queryDTO.getWarningEndDate() != null) {
			dc.add(Restrictions.and(
					Restrictions.le("warningDate",
							queryDTO.getWarningEndDate()),
					Restrictions.ge("warningDate",
							queryDTO.getWarningDate())));
		}
		return dc;
	}
	/**
	 * 搜索回收时间
	 * @param queryDTO
	 * @param dc
	 * @return
	 */
	private DetachedCriteria searchRecoverTime(CIQueryDTO queryDTO, DetachedCriteria dc) {
		if (queryDTO.getRecoverTime() != null
				&& queryDTO.getRecoverTimeEnd() == null) {
			dc.add(Restrictions.ge("recoverTime", queryDTO.getRecoverTime()));
		}
		if (queryDTO.getRecoverTime() == null
				&& queryDTO.getRecoverTimeEnd() != null) {
			dc.add(Restrictions.le("recoverTime",
					queryDTO.getRecoverTimeEnd()));
		}

		if (queryDTO.getRecoverTime() != null
				&& queryDTO.getRecoverTimeEnd() != null) {
			dc.add(Restrictions.and(
					Restrictions.le("recoverTime",
							queryDTO.getRecoverTimeEnd()),
					Restrictions.ge("recoverTime",
							queryDTO.getRecoverTime())));
		}
		return dc;
	}
	/**
	 * 查询报废时间
	 * @param queryDTO
	 * @param dc
	 * @return
	 */
	private DetachedCriteria searchWasteTime(CIQueryDTO queryDTO, DetachedCriteria dc) {
		if (queryDTO.getWasteTime() != null
				&& queryDTO.getWasteTimeEnd() == null) {
			dc.add(Restrictions.ge("wasteTime", queryDTO.getWasteTime()));
		}
		if (queryDTO.getWasteTime() == null
				&& queryDTO.getWasteTimeEnd() != null) {
			dc.add(Restrictions.le("wasteTime", queryDTO.getWasteTimeEnd()));
		}

		if (queryDTO.getWasteTime() != null
				&& queryDTO.getWasteTimeEnd() != null) {
			dc.add(Restrictions.and(Restrictions.le("wasteTime",
					queryDTO.getWasteTimeEnd()), Restrictions.ge(
					"wasteTime", queryDTO.getWasteTime())));
		}
		return dc;
	}
	/**
	 * 预计回收时间
	 * @param queryDTO
	 * @param dc
	 * @return
	 */
	private DetachedCriteria searchExpectedRecoverTime(CIQueryDTO queryDTO,
			DetachedCriteria dc) {
		if (queryDTO.getExpectedRecoverTime() != null
				&& queryDTO.getExpectedRecoverTimeEnd() == null) {
			dc.add(Restrictions.ge("expectedRecoverTime",
					queryDTO.getExpectedRecoverTime()));
		}
		if (queryDTO.getExpectedRecoverTime() == null
				&& queryDTO.getExpectedRecoverTimeEnd() != null) {
			dc.add(Restrictions.le("expectedRecoverTime",
					queryDTO.getExpectedRecoverTimeEnd()));
		}

		if (queryDTO.getExpectedRecoverTime() != null
				&& queryDTO.getExpectedRecoverTimeEnd() != null) {
			dc.add(Restrictions.and(
					Restrictions.le("expectedRecoverTime",
							queryDTO.getExpectedRecoverTimeEnd()),
					Restrictions.ge("expectedRecoverTime",
							queryDTO.getExpectedRecoverTime())));
		}
		return dc;
	}
	/**
	 * 查询创建时间
	 * @param queryDTO
	 * @param dc
	 * @return
	 */
	private DetachedCriteria searchCreateTime(CIQueryDTO queryDTO, DetachedCriteria dc) {
		if (queryDTO.getCreateTime() != null
				&& queryDTO.getCreateTimeEnd() == null) {
			dc.add(Restrictions.ge("createTime", queryDTO.getCreateTime()));
		}
		if (queryDTO.getCreateTime() == null
				&& queryDTO.getCreateTimeEnd() != null) {
			Calendar endTimeCl = new GregorianCalendar();
			endTimeCl.setTime(queryDTO.getCreateTimeEnd());
			endTimeCl.set(Calendar.DATE, endTimeCl.get(Calendar.DATE) + 1);
			dc.add(Restrictions.le("createTime", endTimeCl.getTime()));
		}

		if (queryDTO.getCreateTime() != null
				&& queryDTO.getCreateTimeEnd() != null) {
			Calendar endTimeCl = new GregorianCalendar();
			endTimeCl.setTime(queryDTO.getCreateTimeEnd());
			endTimeCl.set(Calendar.DATE, endTimeCl.get(Calendar.DATE) + 1);
			dc.add(Restrictions.and(
					Restrictions.le("createTime", endTimeCl.getTime()),
					Restrictions.ge("createTime", queryDTO.getCreateTime())));
		}
		return dc;
	}
	/**
	 * 最后更新时间
	 * @param queryDTO
	 * @param dc
	 * @return
	 */
	private DetachedCriteria searchLastUpdateTime(CIQueryDTO queryDTO, DetachedCriteria dc) {
		if (queryDTO.getLastUpdateTime() != null
				&& queryDTO.getLastUpdateTimeEnd() == null) {
			dc.add(Restrictions.ge("lastUpdateTime",
					queryDTO.getWasteTime()));
		}
		if (queryDTO.getLastUpdateTime() == null
				&& queryDTO.getLastUpdateTimeEnd() != null) {
			Calendar endTimeCl = new GregorianCalendar();
			endTimeCl.setTime(queryDTO.getLastUpdateTimeEnd());
			endTimeCl.set(Calendar.DATE, endTimeCl.get(Calendar.DATE) + 1);
			dc.add(Restrictions.le("lastUpdateTime", endTimeCl.getTime()));
		}

		if (queryDTO.getLastUpdateTime() != null
				&& queryDTO.getLastUpdateTimeEnd() != null) {
			Calendar endTimeCl = new GregorianCalendar();
			endTimeCl.setTime(queryDTO.getLastUpdateTimeEnd());
			endTimeCl.set(Calendar.DATE, endTimeCl.get(Calendar.DATE) + 1);
			dc.add(Restrictions.and(
					Restrictions.le("lastUpdateTime", endTimeCl.getTime()),
					Restrictions.ge("lastUpdateTime",
							queryDTO.getLastUpdateTime())));
		}
		return dc;
	}
	/**
	 * 购买日期
	 * @param queryDTO
	 * @param dc
	 * @return
	 */
	private DetachedCriteria searchBuyTime(CIQueryDTO queryDTO, DetachedCriteria dc) {
		if (queryDTO.getBuyDate() != null
				&& queryDTO.getBuyEndDate() == null) {
			dc.add(Restrictions.ge("buyDate", queryDTO.getBuyDate()));
		}
		if (queryDTO.getBuyDate() == null
				&& queryDTO.getBuyEndDate() != null) {
			dc.add(Restrictions.le("buyDate", queryDTO.getBuyEndDate()));
		}
		if (queryDTO.getBuyDate() != null
				&& queryDTO.getBuyEndDate() != null) {
			dc.add(Restrictions.and(
					Restrictions.le("buyDate", queryDTO.getBuyEndDate()),
					Restrictions.ge("buyDate", queryDTO.getBuyDate())));
		}
		return dc;
	}
	/**
	 * 到货日期
	 * @param queryDTO
	 * @param dc
	 * @return
	 */
	private DetachedCriteria searchArriveTime(CIQueryDTO queryDTO, DetachedCriteria dc) {
		if (queryDTO.getArrivalDate() != null
				&& queryDTO.getArrivalEndDate() == null) {
			dc.add(Restrictions.ge("arrivalDate", queryDTO.getArrivalDate()));
		}
		if (queryDTO.getArrivalDate() == null
				&& queryDTO.getArrivalEndDate() != null) {
			dc.add(Restrictions.le("arrivalDate",
					queryDTO.getArrivalEndDate()));
		}
		if (queryDTO.getArrivalDate() != null
				&& queryDTO.getArrivalEndDate() != null) {
			dc.add(Restrictions.and(
					Restrictions.le("arrivalDate",
							queryDTO.getArrivalEndDate()),
					Restrictions.ge("arrivalDate",
							queryDTO.getArrivalDate())));
		}
		return dc;
	}

	/**
	 * 基础属性
	 * @param queryDTO
	 * @param dc
	 */
	private DetachedCriteria searchBaseAttribute(CIQueryDTO queryDTO,
			 DetachedCriteria dc) {
		if (queryDTO.getCompanyNos() != null
				&& queryDTO.getCompanyNos().length > 0) {// 所属客户
			dc.add(Restrictions.in("companyNo", queryDTO.getCompanyNos()));
		}
		if (queryDTO.getCompanyNo() != null) {
			dc.add(Restrictions.eq("companyNo", queryDTO.getCompanyNo()));
		}
		
		if (StringUtils.hasText(queryDTO.getCiname())) {// 配置项名称
			dc.add(Restrictions.like("ciname", queryDTO.getCiname(),
					MatchMode.ANYWHERE));
		}
		if (StringUtils.hasText(queryDTO.getCino())) {// 配置项编号
			dc.add(Restrictions.like("cino", queryDTO.getCino(),
					MatchMode.ANYWHERE));
		}
		if (StringUtils.hasText(queryDTO.getModel())) {// 型号
			dc.add(Restrictions.like("model", queryDTO.getModel(),
					MatchMode.ANYWHERE));
		}
		if (StringUtils.hasText(queryDTO.getPoNo())) {// 订单号
			dc.add(Restrictions.like("poNo", queryDTO.getPoNo(),
					MatchMode.ANYWHERE));
		}
		if (StringUtils.hasText(queryDTO.getSerialNumber())) {// 序列号
			dc.add(Restrictions.like("serialNumber",
					queryDTO.getSerialNumber(), MatchMode.ANYWHERE));
		}
		if (StringUtils.hasText(queryDTO.getBarcode())) {// 条形码
			dc.add(Restrictions.like("barcode", queryDTO.getBarcode(),
					MatchMode.ANYWHERE));
		}
		if (StringUtils.hasText(queryDTO.getUserName())) {// 使用人
			String[] userNames = queryDTO.getUserName().split(";");
			if (userNames.length >= 2) {
				dc.add(Restrictions.in("userName", userNames));
			} else {
				dc.add(Restrictions.like("userName",
						queryDTO.getUserName(), MatchMode.ANYWHERE));
			}
		}
		if (MathUtils.isLongEmpty(queryDTO.getCiId())) {
			dc.add(Restrictions.eq("ciId", queryDTO.getCiId()));
		}

		// CDI
		if (StringUtils.hasText(queryDTO.getCDI())) {
			dc.add(Restrictions.like("CDI", queryDTO.getCDI(),
					MatchMode.ANYWHERE));
		}

		// Work Number
		if (StringUtils.hasText(queryDTO.getWorkNumber())) {
			dc.add(Restrictions.like("workNumber",
					queryDTO.getWorkNumber(), MatchMode.ANYWHERE));
		}

		// Project
		if (StringUtils.hasText(queryDTO.getProject())) {
			dc.add(Restrictions.like("project", queryDTO.getProject(),
					MatchMode.ANYWHERE));
		}

		// 来源单位
		if (StringUtils.hasText(queryDTO.getSourceUnits())) {
			dc.add(Restrictions.like("sourceUnits",
					queryDTO.getSourceUnits(), MatchMode.ANYWHERE));
		}

		// 使用权限
		if (StringUtils.hasText(queryDTO.getUsePermissions())) {
			dc.add(Restrictions.like("usePermissions",
					queryDTO.getUsePermissions(), MatchMode.ANYWHERE));
		}

		// 部门
		if (StringUtils.hasText(queryDTO.getDepartment())) {
			dc.add(Restrictions.like("department",
					queryDTO.getDepartment(), MatchMode.ANYWHERE));
		}

		// 是否与财务对应

		if (queryDTO.getFinanceCorrespond() != null) {
			boolean result = false;
			if (queryDTO.getFinanceCorrespond() == 1) {
				result = true;
			} else if (queryDTO.getFinanceCorrespond() == 2) {
				result = false;
			}
			dc.add(Restrictions.eq("financeCorrespond", result));
		}

		// 原使用者originalUser
		if (StringUtils.hasText(queryDTO.getOriginalUser())) {
			dc.add(Restrictions.like("originalUser",
					queryDTO.getOriginalUser(), MatchMode.ANYWHERE));
		}
		// 资产原值
		if (queryDTO.getAssetsOriginalValue() != null
				&& queryDTO.getAssetsOriginalEndValue() != null) {
			dc.add(Restrictions.between("assetsOriginalValue",
					queryDTO.getAssetsOriginalValue(),
					queryDTO.getAssetsOriginalEndValue()));
		}

		// ACL权限
		if (queryDTO.getCiIds() != null && queryDTO.getCiIds().size() > 0) {
			dc.add(Restrictions.in("ciId", queryDTO.getCiIds()));
		}
		return dc;
	}
	
	/**
	 * 查询关联项
	 * @param queryDTO
	 * @param dc
	 */
	private DetachedCriteria searchRelation(CIQueryDTO queryDTO,  DetachedCriteria dc) {
		Long[] categoryNo = null;
		// 分类权限条件+分类查询
		List<Long> categroyNoList = new ArrayList<Long>();
		if (queryDTO.getCategoryNos() != null
				&& queryDTO.getCategoryNos().length > 0) {// 如果分类条件不为空，分类条件与权限分类合并

			boolean categoryResIsNull = queryDTO.getCategoryRes() != null
					&& queryDTO.getCategoryRes().length > 0;
			for (Long no : queryDTO.getCategoryNos()) {
				if (categoryResIsNull) {
					for (Long nos : queryDTO.getCategoryRes()) {
						if (no.toString().equals(nos.toString())) {// 判断分类NO是否在查看权限分类内
							categroyNoList.add(no);
						}
					}

				}
			}
		} else {// 如果分类条件为空,只有权限分类条件
			if (queryDTO.getCategoryRes() != null
					&& queryDTO.getCategoryRes().length > 0) {// 权限分类
																// 不空，则添加到分类list中
				for (Long no : queryDTO.getCategoryRes()) {
					categroyNoList.add(no);
				}
			}
		}
		if (categroyNoList != null && categroyNoList.size() > 0) {// 对分类NO进行查询条件构建
			categoryNo = (Long[]) categroyNoList.toArray(new Long[categroyNoList.size()]);
			
			if (categoryNo != null && categoryNo.length > 0) {
				dc.createAlias("category", "ct").add(
						Restrictions.in("ct.cno", categoryNo));
			}
		} else {// 如果没有任何分类，则查询结果为0

			Long[] defaultNo = new Long[1];
			defaultNo[0] = 0L;
			dc.createAlias("category", "ct").add(
					Restrictions.in("ct.cno", defaultNo));
		}
		if (StringUtils.hasText(queryDTO.getOwner())) {// 拥有者
			String[] owners = queryDTO.getOwner().split(";");
			if (owners.length >= 2) {
				dc.add(Restrictions.in("owner", owners));
			} else {
				dc.add(Restrictions.like("owner", queryDTO.getOwner(),
						MatchMode.ANYWHERE));
			}
		}
		if (MathUtils.isLongEmpty(queryDTO.getBrandId())) {// 品牌
			dc.createAlias("brand", "brandId")
					.add(Restrictions.eq("brandId.dcode",
							queryDTO.getBrandId()));
		}
		if (MathUtils.isLongEmpty(queryDTO.getStatusId())
				|| (queryDTO.getGroupField()!=null && queryDTO.getGroupField().equals("status"))
				|| (queryDTO.getStatusId()!=null && queryDTO.getStatusId() == 0 && StringUtils.hasText(queryDTO.getLabel()) && "unknown".equals(queryDTO.getLabel()))) {// 状态
			dc.createAlias("status", "statusId",CriteriaSpecification.LEFT_JOIN);
			if (MathUtils.isLongEmpty(queryDTO.getStatusId())){
				dc.add(Restrictions.eq("statusId.dcode",queryDTO.getStatusId()));
			}else if(queryDTO.getStatusId()!=null && queryDTO.getStatusId() == 0 && StringUtils.hasText(queryDTO.getLabel()) && "unknown".equals(queryDTO.getLabel())){
				dc.add(Restrictions.isNull("statusId.dcode"));
			}
		}
		if (MathUtils.isLongEmpty(queryDTO.getSystemPlatformId())) {
			dc.createAlias("systemPlatform", "systemPlatformId").add(
					Restrictions.eq("systemPlatformId.dcode",
							queryDTO.getSystemPlatformId()));
		}
		if (MathUtils.isLongEmpty(queryDTO.getLocId())
				|| (queryDTO.getGroupField()!=null && queryDTO.getGroupField().equals("loc"))
				|| (queryDTO.getLocId()!=null && queryDTO.getLocId() == 0 && StringUtils.hasText(queryDTO.getLabel()) && "unknown".equals(queryDTO.getLabel()))) {// 位置
			dc.createAlias("loc", "locId",CriteriaSpecification.LEFT_JOIN);
			if (MathUtils.isLongEmpty(queryDTO.getLocId())){
				dc.add(Restrictions.eq("locId.eventId", queryDTO.getLocId()));
			}else if(queryDTO.getLocId()!=null && queryDTO.getLocId() == 0 && StringUtils.hasText(queryDTO.getLabel()) && "unknown".equals(queryDTO.getLabel())){
				dc.add(Restrictions.isNull("locId.eventId"));
			}
		}
		if (MathUtils.isLongEmpty(queryDTO.getProviderId())) {// 供应商
			dc.createAlias("provider", "pro").add(
					Restrictions.eq("pro.dcode", queryDTO.getProviderId()));
		}
		return dc;
	}

	/**
	 * 软件使用许可统计
	 * 
	 * @param softwareName
	 * @return String
	 */
	public Integer softwareLicenseUseCount(String softwareName) {

		 DetachedCriteria dc = DetachedCriteria.forClass(CI.class);

		dc.createAlias("ciSoftwares", "sw");
		dc.add(Restrictions.eq("sw.softwareName", softwareName));
		// dc.setProjection(Projections.rowCount());

		return getHibernateTemplate().findByCriteria(dc).size();
	};

	/**
	 * 根据获取某一用户关联的配置项
	 * 
	 * @param start
	 * @param limit
	 * @return String
	 */
	public PageDTO findPageConfigureItemByUser(UserDTO userDTO, int start,
			int limit, String sidx, String sord, CIQueryDTO ciQueryDTO) {
		DetachedCriteria dc = DetachedCriteria.forClass(CI.class);
		PageDTO p = new PageDTO();
		Disjunction dj = Restrictions.disjunction();
		dc.add(dj);
		if (ciQueryDTO != null) {
			if (StringUtils.hasText(ciQueryDTO.getCiname())) {// 配置项名称
				dc.add(Restrictions.like("ciname", ciQueryDTO.getCiname(),
						MatchMode.ANYWHERE));
			}
			if (StringUtils.hasText(ciQueryDTO.getCino())) {// 配置项编号
				dc.add(Restrictions.like("cino", ciQueryDTO.getCino(),
						MatchMode.ANYWHERE));
			}
			dj.add(Restrictions.eq("userName", ciQueryDTO.getLoginName()));
			dj.add(Restrictions.eq("owner", ciQueryDTO.getLoginName()));
			// 排序
			dc = DaoUtils.orderBy(sidx, sord, dc);
			p = super.findPageByCriteria(dc, start, limit);
		}
		return p;
	}

	/**
	 * 根据ID查找.
	 * 
	 * @param ids
	 * @return String
	 */
	@SuppressWarnings("unchecked")
	public List<CI> findByIds(Long[] ids) {

		DetachedCriteria dc = DetachedCriteria.forClass(CI.class);

		if (ids != null && ids.length > 0) {

			dc.add(Restrictions.in("ciId", ids));
			return super.getHibernateTemplate().findByCriteria(dc);
		}

		return null;
	}

	/**
	 * 根据硬件中的计算机名进行搜索查询
	 * 
	 * @param companyName
	 * @return String
	 */
	@SuppressWarnings("unchecked")
	public List<CI> findAllByCompanyName(String companyName) {
		 DetachedCriteria dc = DetachedCriteria.forClass(CI.class);
		dc.createAlias("hardware", "hd");
		dc.add(Restrictions.eq("hd.computerSystem_name", companyName));
		return super.getHibernateTemplate().findByCriteria(dc);
	}

	

	/**
	 * 查询生命周期到期的配置项
	 */
	@SuppressWarnings("unchecked")
	public List<CI> calcCiLifeCycle() {
		String hql = " from CI c where (year(CURRENT_DATE()) - year(c.arrivalDate))*12+(month(CURRENT_DATE()) - month(c.arrivalDate)) > c.lifeCycle "
				+ "or ((year(CURRENT_DATE()) - year(c.arrivalDate))*12+(month(CURRENT_DATE()) - month(c.arrivalDate)) = c.lifeCycle and day(CURRENT_DATE()) > day(c.arrivalDate))";
		return getHibernateTemplate().find(hql);
	}

	/**
	 * 查询报修期到期的配置项
	 */
	@SuppressWarnings("unchecked")
	public List<CI> calcCiWarranty() {
		String hql = " from CI c where (year(CURRENT_DATE()) - year(c.arrivalDate))*12+(month(CURRENT_DATE()) - month(c.arrivalDate)) > c.warranty "
				+ "or ((year(CURRENT_DATE()) - year(c.arrivalDate))*12+(month(CURRENT_DATE()) - month(c.arrivalDate)) = c.warranty and day(CURRENT_DATE()) > day(c.arrivalDate))";
		return getHibernateTemplate().find(hql);
	}

	/**
	 * 查询预警期到期的配置项
	 */
	@SuppressWarnings("unchecked")
	public List<CI> calcWarningDate() {
		String hql = " from CI c where CURRENT_DATE() > c.warningDate";
		return getHibernateTemplate().find(hql);
	}

	/**
	 * 分组统计配置项
	 * 
	 * @param qdto
	 *            统计条件CIQueryDTO
	 * @return
	 */
	public List<StatResultDTO> groupStatCiByCompanyNo(CIQueryDTO qdto) {
		 DetachedCriteria dc = DetachedCriteria.forClass(CI.class);
		// 公司条件
		if (qdto.getCompanyNos() != null && qdto.getCompanyNos().length > 0) {
			dc.add(Restrictions.in("companyNo", qdto.getCompanyNos()));
		}
		// 分类条件
		if (qdto.getCategoryRes() != null && qdto.getCategoryRes().length > 0) {
			dc.createAlias("category", "ct").add(
					Restrictions.in("ct.cno", qdto.getCategoryRes()));
		}else{
			Long[] defaultNo = new Long[1];
			defaultNo[0] = 0L;
			dc.createAlias("category", "ct").add(
					Restrictions.in("ct.cno", defaultNo));
		}
		dc.setProjection(Projections.projectionList()
				.add(Projections.groupProperty("companyNo").as("id"))
				.add(Projections.alias(Projections.rowCount(), "quantity")));

		dc.setResultTransformer(Transformers.aliasToBean(StatResultDTO.class));
		List<StatResultDTO> statResult = (List<StatResultDTO>) getHibernateTemplate()
				.findByCriteria(dc);
		return statResult;
	}
	
	
	/**
	 * 配置项分页查询
	 * 
	 * @return PageDTO：
	 */
	@Transactional
	public Integer findAllCICount(CIQueryDTO queryDTO) {

		DetachedCriteria dc = DetachedCriteria.forClass(CI.class);
		/***
		 * Set data mode
		 */
		if (queryDTO != null) {
			
			//查询关联项
			dc = searchRelation(queryDTO, dc);

			//基础属性
			dc = searchBaseAttribute(queryDTO, dc);

			//相关时间查询
			dc = searchByTime(queryDTO, dc);

		}
		List<CI> list = super.getHibernateTemplate().findByCriteria(dc);
		return list!=null?list.size():0;
	}

	/*public Map<String,CI> findBy(String propertyName, Object[] value) {
		List<CI> cis = super.findBy(propertyName, value);
		Map<String, CI> ciMap = Maps.newHashMap();
		if( cis != null ){
			for (CI ci : cis) {
				try {
					ciMap.put(BeanUtils.getProperty(ci, propertyName), ci);
				} catch (Exception e) {}
			}
		}
		return ciMap;
	}*/
}
